package service

import (
	"project-im/config"
	"project-im/internal/model/dao"
)

func FindUserId(id int) (*dao.ImUser, string) {
	var user *dao.ImUser
	err := config.DB.Model(&dao.ImUser{}).Where("id=?", id).Limit(1).Find(&user).Error
	if err != nil {
		config.DB.Rollback()
		return nil, "用户不存在"
	}
	if user.ID == 0 {
		config.DB.Rollback()
		return nil, "用户不存在"
	}
	return user, ""
}

func FindFriend(userId int, friendId int) *dao.ImFriend {
	var friend *dao.ImFriend
	config.DB.Model(&dao.ImFriend{}).Where("user_id=?&&friend_id=?", userId, friendId).Limit(1).Find(&friend)
	return friend
}
func FriendAdd(userId int, friendId int) string {
	tx := config.DB.Begin()
	_, s := FindUserId(userId)
	findUserId, s1 := FindUserId(friendId)
	if s != "" || s1 != "" {
		tx.Rollback()
		return "用户不存在"
	}
	findFriend := FindFriend(userId, friendId)
	if findFriend.ID != 0 {
		tx.Rollback()
		return "已经添加过好友了"
	}
	findFriends := FindFriend(friendId, userId)
	if findFriends.ID != 0 {
		tx.Rollback()
		return "已经添加过好友了"
	}
	friend := dao.ImFriend{
		UserId:          userId,
		FriendId:        friendId,
		FriendNickName:  findUserId.NickName,
		FriendHeadImage: findUserId.HeadImage,
	}
	err := config.DB.Model(&dao.ImFriend{}).Create(&friend).Error
	if err != nil {
		tx.Rollback()
		return "好友添加失败"
	}
	friend1 := dao.ImFriend{
		UserId:          friendId,
		FriendId:        userId,
		FriendNickName:  findUserId.NickName,
		FriendHeadImage: findUserId.HeadImage,
	}
	err = config.DB.Model(&dao.ImFriend{}).Create(&friend1).Error
	if err != nil {
		tx.Rollback()
		return "好友添加失败"
	}
	tx.Commit()
	return ""
}
